from fastapi import APIRouter, Depends
from app.schemas.send import sendMessagesRequest
from app.services.sendService import create_send_service, SendService
from app.common.result import Result
from typing import Optional
import logging

router = APIRouter()
logger = logging.getLogger(__name__)

# 全局服务实例
_send_service: Optional[SendService] = None

def get_send_service() -> SendService:
    """
    获取或创建发送服务实例
    使用单例模式避免重复创建浏览器实例
    """
    global _send_service
    if _send_service is None:
        try:
            _send_service = create_send_service()
        except Exception as e:
            logger.error(f"创建发送服务失败: {str(e)}")
            raise
    return _send_service

@router.post("/sendMessages")
async def send_messages(
    request: sendMessagesRequest,
    service: SendService = Depends(get_send_service)
):
    """
    发送选中的信息到平台（目前是微博）
    
    Args:
        request: 包含要发送的消息列表的请求对象
        service: 注入的发送服务实例
        
    Returns:
        Result: 包含发送结果的响应对象
    """
    try:
        # 直接使用消息列表，因为现在已经是字符串列表了
        comments = request.messages
        
        # 记录开始发送
        logger.info(f"开始发送 {len(comments)} 条消息")
        
        # 调用服务发送评论
        results = service.send_comments(comments)
        
        # 构建响应数据
        response_data = {
            "total": results["total"],
            "success": results["success"],
            "failed": results["failed"],
            "failed_messages": results["failed_comments"]  # 直接使用失败评论列表
        }
        
        # 根据发送结果返回不同的响应
        if results["failed"] == 0:
            return Result.success(
                data=response_data,
                msg=f"成功发送 {results['success']} 条消息"
            )
        elif results["success"] == 0:
            return Result.fail(
                msg=f"发送失败，所有 {results['total']} 条消息均未发送成功",
                data=response_data
            )
        else:
            return Result.success(
                data=response_data,
                msg=f"部分发送成功：成功 {results['success']} 条，失败 {results['failed']} 条"
            )
            
    except Exception as e:
        logger.error(f"发送消息时发生错误: {str(e)}")
        return Result.fail(msg=f"系统错误: {str(e)}")

@router.on_event("shutdown")
async def shutdown_event():
    """
    应用关闭时清理资源
    """
    global _send_service
    if _send_service is not None:
        try:
            _send_service.close()
            _send_service = None
            logger.info("发送服务已关闭")
        except Exception as e:
            logger.error(f"关闭发送服务时发生错误: {str(e)}")
